package com.example.demo.service.impl;

import com.example.demo.service.ScriptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

@Slf4j
@Service
public class ScriptServiceImpl implements ScriptService {

    private final RestTemplate restTemplate = new RestTemplate();

    @Override
    public String runLogin(String proxyIp, String location,String userid) {
        // 准备表单数据
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        formData.add("url", proxyIp);
        formData.add("location", location);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 创建HttpEntity包含请求体和请求头
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);

        String url = "http://"+location+":9000/yuluo/net/startLogin";

        // 发送POST请求并获取响应
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

        // 检查响应状态码
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            String responseBody = responseEntity.getBody();
            log.info("POST请求成功！");
            log.info("服务器响应：" + responseBody);
            return responseBody;
        } else {
            log.error("POST请求失败，错误代码：" + responseEntity.getStatusCode());
        }
        return null;


    }

    @Override
    public void runLocation() {
        // Node.js脚本的路径
        String nodeScriptPath = "path/to/your/script.js";

        // Node.js执行命令，假设Node.js已经安装在环境路径中
        String nodeCommand = "node";

        // 构建命令
        ProcessBuilder processBuilder = new ProcessBuilder(nodeCommand, nodeScriptPath);

        // 将错误流合并到标准输出流中
        processBuilder.redirectErrorStream(true);

        // 启动Node.js脚本
        try {
            Process process = processBuilder.start();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
